<template>
  <div class="classify-container">
    <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
      <!-- 表格区域 -->
      <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
        <template #header>
          <div class="flex items-center justify-between">
            <p>分类管理</p>
            <ElButton type="primary" size="small" @click="handleAddTopCategory">添加</ElButton>
          </div>
        </template>

        <!-- 懒加载的树形表格 -->
        <div class="h-[calc(100%-50px)]">
          <ElTable
            :data="categoryList"
            height="360px"
            border
            class="sm:h-full"
            row-key="id"
            lazy
            :load="loadCategoryChildren"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            v-loading="loading"
          >
            <ElTableColumn prop="categoryName" label="分类名称" />
            <ElTableColumn prop="orderNum" label="排序" />
            <ElTableColumn prop="status" label="状态" #default="scope">
              <ElTag :type="scope.row.status === 1 ? 'success' : 'info'">
                {{ scope.row.status === 1 ? '正常' : '停用' }}
              </ElTag>
            </ElTableColumn>
            <ElTableColumn prop="createTime" label="创建时间" />
            <ElTableColumn label="操作" align="center" width="300" #default="scope">
              <div class="flex-center justify-center gap-8px">
                <ElButton type="primary" plain size="small" @click="handleAddSubCategory(scope.row)">
                  添加子目录
                </ElButton>
                <ElButton type="warning" plain size="small" @click="handleEditCategory(scope.row)">
                  编辑
                </ElButton>
                <ElPopconfirm title="确定要删除该分类吗？" @confirm="handleDeleteCategory(scope.row)">
                  <template #reference>
                    <ElButton type="danger" plain size="small">删除</ElButton>
                  </template>
                </ElPopconfirm>
              </div>
            </ElTableColumn>
          </ElTable>
        </div>
      </ElCard>
    </div>

    <!-- 分类表单对话框 -->
    <ElDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="30%"
      destroy-on-close
      append-to-body
    >
      <ElForm ref="formRef" :model="categoryForm" label-width="120px" :rules="formRules">
        <ElFormItem label="分类名称" prop="categoryName">
          <ElInput v-model="categoryForm.categoryName" placeholder="请输入分类名称" />
        </ElFormItem>
        <ElFormItem v-if="!categoryForm.hasChildren" label="上级分类" prop="categoryId">
          <ElTreeSelect
            v-model="categoryForm.categoryId"
            :data="categoryOptions"
            :props="{ value: 'id', label: 'name', isLeaf: 'leaf' }"
            :load="loadSelectNodes"
            lazy
            clearable
            @visible-change="handleVisibleChange"
            value-key="id"
            placeholder="选择上级分类"
            check-strictly
          />
        </ElFormItem>
        <ElFormItem label="排序" prop="orderNum">
          <ElInputNumber v-model="categoryForm.orderNum" :min="0" :max="100" />
        </ElFormItem>
        <ElFormItem label="状态" prop="status">
          <ElRadioGroup v-model="categoryForm.orderNum">
            <ElRadio :label="1">正常</ElRadio>
            <ElRadio :label="0">停用</ElRadio>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem>
          <div class="flex justify-center gap-12px">
            <ElButton type="primary" @click="submitForm" :loading="submitting">提交</ElButton>
            <ElButton @click="dialogVisible = false">取消</ElButton>
          </div>
        </ElFormItem>
      </ElForm>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { PictureById, findAll, SavePicture, UpdatePicture, RemovePicture } from '@/service/api/material/classify';
import { useCategoryTree } from './composables/useCategoryTree';

// 定义类型
interface CategoryItem {
  id: string | number;
  categoryName: string;
  status: number;
  orderNum: number;
  categoryId: string | number | null;
  hasChildren?: boolean;
  createTime?: string;
  children?: CategoryItem[];
}

interface CategoryOption {
  id: string | number;
  name: string;
  leaf: boolean;
  children?: CategoryOption[];
}

interface QueryParams {
  categoryName?: string;
  status?: number;
}

// 使用组合式函数管理树形数据加载
const { 
  loadCategoryChildren, 
  loadSelectNodes, 
  categoryOptions, 
  isOptionsLoaded,
  resetOptionsLoaded
} = useCategoryTree();

// 状态变量
const categoryList = ref<CategoryItem[]>([]);
const loading = ref(false);
const submitting = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref();

// 查询参数
const queryParams = ref<QueryParams>({
  categoryName: '',
  status: -1
});

// 表单数据
const categoryForm = ref<CategoryItem>({
  id: '',
  categoryName: '',
  status: 1,
  orderNum: 1,
  categoryId: null,
  hasChildren: false
});

// 表单验证规则
const formRules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
};

// 页面初始化加载数据
onMounted(() => {
  fetchCategoryList();
});

// 组件卸载前清理资源
onBeforeUnmount(() => {
  categoryList.value = [];
  resetOptionsLoaded();
  dialogVisible.value = false;
});

// 获取分类列表数据
const fetchCategoryList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params: QueryParams = {};
    if (queryParams.value.categoryName) {
      params.categoryName = queryParams.value.categoryName;
    }
    if (queryParams.value.status !== -1) {
      params.status = queryParams.value.status;
    }
    
    const { code, data, message } = await findAll(params);
    categoryList.value = data || []; // 更新表格数据
  } catch (error) {
    console.error('获取分类列表失败:', error);
    ElMessage.error('获取分类列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 当下拉框显示/隐藏时触发
const handleVisibleChange = async (visible: boolean) => {
  if (visible && !isOptionsLoaded.value) {
    try {
      const res = await PictureById(0);
      categoryOptions.value = res.data.map((item: any) => ({
        id: item.id,
        name: item.categoryName,
        leaf: !item.hasChildren
      }));
      isOptionsLoaded.value = true; // 标记为已加载
    } catch (error) {
      console.error("加载分类选项失败:", error);
      ElMessage.error('加载分类选项失败，请稍后重试');
    }
  }
};

// 提交表单数据
const submitForm = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitting.value = true;
    
    let result;
    // 根据ID判断是新增还是修改
    if (!categoryForm.value.id) {  
      result = await SavePicture(categoryForm.value);
    } else {
      result = await UpdatePicture(categoryForm.value);
    }
    
    const { code, message } = result.response.data;
    if (code === "0000") {
      dialogVisible.value = false;
      ElMessage.success('操作成功');
      // 刷新数据
      await fetchCategoryList();
    } else {
      ElMessage.error(message || '操作失败');
    }
  } catch (error) {
    console.error('提交数据出错:', error);
    ElMessage.error('表单验证失败或操作失败，请检查表单并重试');
  } finally {
    submitting.value = false;
  }
};

// 删除分类
const handleDeleteCategory = async (row: CategoryItem) => {
  try {
    const data = await RemovePicture(row.id);
    const { code, message } = data.response.data;        
    if (code === "0000") {
      ElMessage.success('删除成功');
      await fetchCategoryList(); // 刷新数据
    } else {
      ElMessage.error(message || '删除失败');
    }
  } catch (error) {
    console.error('删除数据出错:', error);
    ElMessage.error('删除失败，请稍后重试');
  }
};

// 编辑分类
const handleEditCategory = async (row: CategoryItem) => {
  try {
    // 处理上级分类ID
    const categoryId = row.categoryId === 0 ? null : row.categoryId;
    
    // 设置表单数据并显示对话框
    categoryForm.value = {
      ...row,
      categoryId
    };
    
    dialogVisible.value = true;
    dialogTitle.value = "修改分类";
  } catch (error) {
    console.error('加载编辑数据出错:', error);
    ElMessage.error('加载数据失败，请稍后重试');
  }
};

// 添加顶级分类
const handleAddTopCategory = () => {
  // 重置表单数据
  categoryForm.value = {
    id: '',
    categoryName: '',
    categoryId: null,
    status: 1,
    orderNum: 1,
    hasChildren: false
  };
  
  // 显示对话框
  dialogVisible.value = true;
  dialogTitle.value = "添加分类";
};

// 添加子分类
const handleAddSubCategory = (row: CategoryItem) => {
  // 设置表单数据
  categoryForm.value = {
    id: '',
    categoryName: '',
    categoryId: row.id,
    status: 1,
    orderNum: 1,
    hasChildren: false
  };
  
  // 显示对话框
  dialogVisible.value = true;
  dialogTitle.value = "添加子分类";
};
</script>

<style lang="scss" scoped>
.classify-container {
  .card-wrapper {
    height: calc(100vh - 180px);
  }
}
</style>